package informationGet.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.supermap.android.commons.EventStatus;
import com.supermap.android.maps.measure.MeasureMode;
import com.supermap.android.maps.measure.MeasureParameters;
import com.supermap.android.maps.measure.MeasureResult;
import com.supermap.android.maps.measure.MeasureService;
import com.supermap.services.components.commontypes.Point2D;
import com.whu.zj.MyApplication;
import com.whu.zj.R;
import com.whu.zj.UIHandler;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import gis.activity.MapShow;
import informationGet.dto.PointXY;
import informationGet.adapter.PickPointsAdatper;
import informationGet.dto.Points;
import informationGet.network.UploadPhotoAndPoints;
import informationGet.util.Coord;
import model.OwnUser;
import utils.TimeUtil;

/**
 * 采集信息
 * Created by Administrator on 2016/3/8.
 */
public class TakeInformationActivity extends UIHandler.BaseActivity {

    Button btn_back;

    final String tempPhotoDir = "/sdcard/zj/imgtmp/";
    final String tempFileName = "temp.jpg";

    View v_imgTake;
    ListView lv_point;
    List<PickPointsAdatper.ItemClass> items = new ArrayList<PickPointsAdatper.ItemClass>();
    PickPointsAdatper pickPointsAdatper = new PickPointsAdatper();

    EditText et_other;
    View v_pickPoint;
    View v_clear;
    View v_upload;

    LocationManager locationManager;
    AlertDialog alertDialog;
    Location location;
    //是否获取到位置
    boolean hasLocation;

    View v_area;

    Button btn_readinfo;

    boolean isTakenImage;

    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.defalut_img) //设置图片在下载期间显示的图片
            .showImageForEmptyUri(R.drawable.defalut_img)//设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.drawable.defalut_img)  //设置图片加载/解码过程中错误时候显示的图片
//    .cacheInMemory(true)//设置下载的图片是否缓存在内存中
//            .cacheOnDisc(true)//设置下载的图片是否缓存在SD卡中
            .considerExifParams(true)  //是否考虑JPEG图像EXIF参数（旋转，翻转）
            .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示
            .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//
            .resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
            .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
            .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
            .build();//构建完成


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_takeinfor);
        initview();
        openGpsListen();

    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == v_imgTake) {
                takePhoto();
            } else if (v == v_pickPoint) {
                takePoint();
            } else if (v == v_clear) {
                clearPoints();
            } else if (v == v_upload) {
                if (isTakenImage)
                    uploadPoints();
                else
                    Toast.makeText(MyApplication.share(), "请先拍照", Toast.LENGTH_SHORT).show();
            } else if (v == v_area) {
                List<Point2D> point2Ds = new ArrayList<Point2D>();
                for (PickPointsAdatper.ItemClass itemClass : pickPointsAdatper.getPointXYs()) {
                    if (itemClass.isChoosed()) {
                        Point2D point2D = new Point2D(itemClass.getPointXY().getX(), itemClass.getPointXY().getY());
                        point2Ds.add(point2D);
                    }
                }

                if (point2Ds.size() == 2) {
                    Point2D[] point2Ds1 = new Point2D[point2Ds.size()];
                    for (int j = 0; j < point2Ds.size(); j++) {
                        Double[] doubles = Coord.Coord2(point2Ds.get(j).x, point2Ds.get(j).y);
                        Point2D point2DTmp = new Point2D(doubles[0], doubles[1]);
                        point2Ds1[j] = point2DTmp;
                    }
                    Measure_distance(point2Ds1);
                } else if (point2Ds.size() > 2) {
                    Point2D[] point2Ds1 = new Point2D[point2Ds.size()];
                    for (int j = 0; j < point2Ds.size(); j++) {
                        Double[] doubles = Coord.Coord2(point2Ds.get(j).x, point2Ds.get(j).y);
                        Point2D point2DTmp = new Point2D(doubles[0], doubles[1]);
                        point2Ds1[j] = point2DTmp;
                    }
                    Measure_Area(point2Ds1);
                }
            } else if (v == btn_back) {
                TakeInformationActivity.this.finish();
            } else if (v == btn_readinfo) {
                Intent intent = new Intent(TakeInformationActivity.this, ReadInfoActivity.class);
                TakeInformationActivity.this.startActivity(intent);
            }
        }
    };


    // 面积量算结果
    public void Measure_Area(com.supermap.services.components.commontypes.Point2D[] ptsTmp) {
        // 构造查询参数
        MeasureParameters parameters = new MeasureParameters();
//        com.supermap.services.components.commontypes.Point2D[] pts = { new com.supermap.services.components.commontypes.Point2D(23, 34), new com.supermap.services.components.commontypes.Point2D(53.55, 12.66), new com.supermap.services.components.commontypes.Point2D(73.88, 12.6),new com.supermap.services.components.commontypes.Point2D(23,34) };
        parameters.point2Ds = ptsTmp;
        MeasureService service = new MeasureService(MapShow.DEFAULT_URL);
        MyMeasureEventListener2 listener = new MyMeasureEventListener2();
        service.process(parameters, listener, MeasureMode.AREA);
    }

    // 量算监听器类
    class MyMeasureEventListener2 extends MeasureService.MeasureEventListener {
        @Override
        public void onMeasureStatusChanged(Object sourceObject, EventStatus status) {
            // 量算结果
            final MeasureResult result = (MeasureResult) sourceObject;
//            Toast.makeText(UploadPoint.this,"面积:"+result.area,Toast.LENGTH_SHORT).show();
            UIHandler.uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    if(result == null)
                    {
                        Toast.makeText(MyApplication.share(),"获取失败",Toast.LENGTH_SHORT).show();
                        return;
                    }
                    new AlertDialog.Builder(TakeInformationActivity.this).
                            setTitle("面积").
                            setMessage(result.area + "平方米")
                            .show();
                }
            });
        }
    }


    // 距离量算结果
    public void Measure_distance(com.supermap.services.components.commontypes.Point2D[] pts) {
        // 构造查询参数
        MeasureParameters parameters = new MeasureParameters();
//        com.supermap.services.components.commontypes.Point2D[] pts = { new com.supermap.services.components.commontypes.Point2D(23, 34), new com.supermap.services.components.commontypes.Point2D(53.55, 12.66) };
        parameters.point2Ds = pts;
        MeasureService service = new MeasureService(MapShow.DEFAULT_URL);
        MyMeasureEventListener listener = new MyMeasureEventListener();
        service.process(parameters, listener, null);

    }

    // 量算监听器类
    class MyMeasureEventListener extends MeasureService.MeasureEventListener {
        @Override
        public void onMeasureStatusChanged(Object sourceObject, EventStatus status) {
            // 量算结果
            final MeasureResult result = (MeasureResult) sourceObject;
            UIHandler.uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    new AlertDialog.Builder(TakeInformationActivity.this).
                            setTitle("距离").
                            setMessage(result.distance + "米")
                            .show();
                }
            });
        }
    }

    // 上传照片和坐标
    private void uploadPoints() {
        v_upload.setEnabled(false);
        UploadPhotoTask uploadPhotoTask = new UploadPhotoTask();
        File file = new File(tempPhotoDir + tempFileName);
        UploadPhotoAndPoints.Upload upload = new UploadPhotoAndPoints.Upload();
        String time = TimeUtil.currentTime2();

        OwnUser ownUser = MyApplication.getOwnUser();
        String account = ownUser.getUser_NickName();
        String realName = ownUser.getUser_RealName();
        String message = et_other.getText().toString();
        List<PointXY> pointXies = new ArrayList<PointXY>();
        for (PickPointsAdatper.ItemClass itemClass : items) {
            if (itemClass.isChoosed()) {
                pointXies.add(itemClass.getPointXY());
            }
        }

        Points points = new Points(account, time, ownUser.getUser_RealName(), JSON.toJSONString(pointXies), realName + "_" + time + ".jpg", message);
        upload.setPoints(points);
        UploadPhotoAndPoints uploadPhotoAndPoints = new UploadPhotoAndPoints(file, upload);
        uploadPhotoTask.setUploadPhotoAndPoints(uploadPhotoAndPoints);
        Toast.makeText(MyApplication.share(),"正在上传，莫慌",Toast.LENGTH_SHORT).show();
        uploadPhotoTask.execute();
    }

    // 清除坐标
    private void clearPoints() {
        items.clear();
        pickPointsAdatper.notifyDataSetChanged();
    }


    // 监听位置信息
    private LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            // 当GPS定位信息发生改变时，更新位置
            System.out.println("位置改变");
            TakeInformationActivity.this.location = location;

            alertDialog.setMessage("位置获取成功！");
            hasLocation = true;
            locationManager.removeUpdates(this);
        }

        @Override
        public void onProviderDisabled(String provider) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onStatusChanged(String provider, int status,
                                    Bundle extras) {
        }
    };

    Criteria c = new Criteria();
    String provider;

    {
        c.setAccuracy(Criteria.ACCURACY_FINE);// 精度高
    }


    // 获取坐标
    private void takePoint() {
        provider = locationManager.getBestProvider(c, false);

        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!gps) {
            Toast.makeText(TakeInformationActivity.this, "请打开gps开关来获取更高精度", Toast.LENGTH_SHORT).show();
            provider = LocationManager.NETWORK_PROVIDER;
        }

        Log.i("provider",provider);
        locationManager.requestLocationUpdates(provider, 0, 0, locationListener);

        alertDialog = new AlertDialog.Builder(TakeInformationActivity.this).setTitle("收集坐标")
                .setMessage("正在获取位置...，请稍等").setPositiveButton("收集", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (hasLocation) {
                            PointXY pointXY = new PointXY();
                            pointXY.setX(location.getLongitude());
                            pointXY.setY(location.getLatitude());
                            PickPointsAdatper.ItemClass itemClass = new PickPointsAdatper.ItemClass();
                            itemClass.setPointXY(pointXY);
                            itemClass.setIsChoosed(true);
                            items.add(itemClass);
                            pickPointsAdatper.notifyDataSetChanged();

                        } else {
                            Toast.makeText(TakeInformationActivity.this, "尚未获取到位置信息", Toast.LENGTH_SHORT).show();
                        }
                        locationManager.removeUpdates(locationListener);
                        TakeInformationActivity.this.hasLocation = false;
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        locationManager.removeUpdates(locationListener);
                        TakeInformationActivity.this.hasLocation = false;
                        dialog.dismiss();
                    }
                }).setCancelable(false).show();
    }

    // 启动获取GPS信息
    public void openGpsListen() {
        // 创建LocationManager对象
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // 判断是否打开GPS或者网络
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!gps) {
            Dialog alertDialog = new AlertDialog.Builder(this).
                    setTitle("提高\"我的位置\"精确度").
                    setMessage("如需获取更精确的位置服务，请您在室外时执行以下操作:\n在位置设置中打开GPS").
                    setIcon(R.drawable.location_mark2).
                    setNeutralButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(myIntent);
                        }
                    }).
                    setNegativeButton("取消", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).
                    create();
            alertDialog.show();
        }


    }

    // 拍照
    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File filedir = new File(tempPhotoDir);
        if (!filedir.exists()) {
            filedir.mkdirs();
        }

        File file = new File(tempPhotoDir + tempFileName);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(intent, 0x02);
    }

    //
    private void initview() {

        v_imgTake = findViewById(R.id.id_img_take);
        v_imgTake.setOnClickListener(onClickListener);

        v_clear = findViewById(R.id.id_v_clear);
        v_clear.setOnClickListener(onClickListener);

        v_upload = findViewById(R.id.id_v_upload);
        v_upload.setOnClickListener(onClickListener);

        lv_point = (ListView) findViewById(R.id.id_lv_points);
        et_other = (EditText) findViewById(R.id.id_et_other);
        v_pickPoint = findViewById(R.id.id_v_pick);
        v_pickPoint.setOnClickListener(onClickListener);

        pickPointsAdatper.setPointXYs(items);
        lv_point.setAdapter(pickPointsAdatper);

        v_area = findViewById(R.id.id_v_area);
        v_area.setOnClickListener(onClickListener);

        btn_back = (Button) findViewById(R.id.id_btn_back);
        btn_back.setOnClickListener(onClickListener);

        btn_readinfo = (Button) findViewById(R.id.id_btn_readInfo);
        btn_readinfo.setOnClickListener(onClickListener);

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0)
            return;
        if (requestCode == 0x02) {
            if (resultCode == RESULT_OK) {
                ImageLoader imageLoader = ImageLoader.getInstance();
                imageLoader.displayImage("file:///mnt/" + tempPhotoDir + tempFileName, (ImageView) v_imgTake, options, simpleImageLoadingListener);
            }
        }

    }


    SimpleImageLoadingListener simpleImageLoadingListener = new SimpleImageLoadingListener() {
        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            super.onLoadingComplete(imageUri, view, loadedImage);
            isTakenImage = true;
        }
    };

    // 上传照片
    public class UploadPhotoTask extends AsyncTask<Object, Integer, Integer> {

        UploadPhotoAndPoints uploadPhotoAndPoints;

        public void setUploadPhotoAndPoints(UploadPhotoAndPoints uploadPhotoAndPoints) {
            this.uploadPhotoAndPoints = uploadPhotoAndPoints;
        }

        @Override
        protected Integer doInBackground(Object[] params) {
            boolean isSuccess = false;
            try {
                isSuccess = uploadPhotoAndPoints.upload();
            } catch (Exception e) {
                e.printStackTrace();
                isSuccess = false;
                return 0;
            }
            return isSuccess ? 1 : 0;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            v_upload.setEnabled(true);
            if (integer == 1) {
                System.out.println("上传成功");
                Toast.makeText(TakeInformationActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                TakeInformationActivity.this.finish();
            }

        }
    }
}
